﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dependencies;

using Autofac;
namespace Zeus.DependencyInjection
{
    public class AutofacWebApiDependencyScope : IDependencyScope
    {
        private bool _disposed;

        readonly ILifetimeScope _lifetimeScope;

        public AutofacWebApiDependencyScope(ILifetimeScope lifetimeScope)
        {
            if (lifetimeScope == null) throw new ArgumentNullException("lifetimeScope");

            _lifetimeScope = lifetimeScope;
        }

        AutofacWebApiDependencyScope()
        {
            Dispose(false);
        }

        public ILifetimeScope LifetimeScope
        {
            get { return _lifetimeScope; }
        }

        public object GetService(Type serviceType)
        {
            return _lifetimeScope.ResolveOptional(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (!_lifetimeScope.IsRegistered(serviceType))
                return Enumerable.Empty<object>();

            var enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(serviceType);
            var instance = _lifetimeScope.Resolve(enumerableServiceType);
            return (IEnumerable<object>)instance;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_lifetimeScope != null)
                    {
                        _lifetimeScope.Dispose();
                    }
                }
                _disposed = true;
            }
        }
    }
}
